package com.weixing.mall.provider.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.AgentAuth;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.provider.model.domain.AgentRebate;
import com.weixing.mall.provider.model.domain.AgentWithdraw;
import com.weixing.mall.provider.model.dto.AgentWithdrawDto;
import com.weixing.mall.provider.model.enums.AgentWithdrawAuditEnum;
import com.weixing.mall.provider.model.query.AgentRebateQuery;
import com.weixing.mall.provider.model.query.AgentWithdrawQuery;
import com.weixing.mall.provider.model.vo.AgentRebateVo;
import com.weixing.mall.provider.model.vo.AgentWithdrawSettleVo;
import com.weixing.mall.provider.model.vo.AgentWithdrawVo;
import com.weixing.mall.provider.service.IAgentAccountService;
import com.weixing.mall.provider.service.IAgentRebateService;
import com.weixing.mall.provider.service.IAgentService;
import com.weixing.mall.provider.service.IAgentWithdrawService;
import com.weixing.mall.provider.support.excel.AgentWithdrawExcelDownData;
import com.weixing.mall.provider.support.excel.AgentWithdrawImportDataListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代理商提现Api
 * @author  wx
 * @date  2019/10/15 16:31
 * @since  1.0
 */
@RestController
@RequestMapping("agent/withdraw")
public class AgentWithdrawController extends BaseController {
    @Autowired
    private IAgentWithdrawService agentWithdrawService;
    @Autowired
    private IAgentAccountService agentAccountService;
    @Autowired
    private IAgentService agentService;
    @Autowired
    private IAgentRebateService agentRebateService;

    /**
     * 代理商提现列表查询
     * @param query  查询参数
     * @return       列表
     */
    @GetMapping("")
    public Result<IPage<AgentWithdrawVo>> List(AgentWithdrawQuery query){
        SysAuth auth = AuthUtil.getSysExt();
        return ResultUtil.success(agentWithdrawService.selectListOfPage(initMpPage(),query,auth));
    }


    /**
     * 代理商提现列表查询--代理用
     *
     * @param query    查询条件
     * @return         列表
     */
    @GetMapping("/agent")
    public Result<IPage<AgentWithdrawVo>> ListForAgent( AgentWithdrawQuery query){
        AgentAuth auth = AuthUtil.getAgentExt();
        query.setAgentId(auth.getAid());
        return ResultUtil.success(agentWithdrawService.selectListOfPage(initMpPage(),query,null));
    }

    /**
     * 客服后台给代理商提现--客服用
     * @param agentId    代理id
     * @param query      查询条件
     * @return           列表
     */
    @GetMapping("/customer/{agentId}")
    public Result<IPage<AgentWithdrawVo>> customer(@PathVariable Long  agentId,AgentWithdrawQuery query){
        query.setAgentId(agentId);
        return ResultUtil.success(agentWithdrawService.selectListOfPage(initMpPage(),query,null));
    }

    /**
     * 客服后台给代理商申请提现--客服新增提现
     *
     * @param dto   参数
     * @return      结果
     */
    @PostMapping("save")
    @NoRepeatSubmit()
    public Result save(AgentWithdrawDto dto){
        SysAuth auth = AuthUtil.getSysExt();
        List<AgentRebate> ttList = agentRebateService.list(new QueryWrapper<AgentRebate>().isNull("out_bill_id").eq("agent_id", dto.getAgentId()));
        if(ttList.size()==0){
            return ResultUtil.error("无可提现金额，请联系管理员");
        }
        agentWithdrawService.save(dto,auth);
        return ResultUtil.success();
    }

    /**
     * 代理商提现审核
     *
     * @param id             id
     * @param auditResult    审核结果
     * @param auditRemark    审核备注
     * @return 结果
     */
    @PostMapping("audit/{id}")
    @NoRepeatSubmit()
    public Result audit( @PathVariable Long id, AgentWithdrawAuditEnum auditResult,String auditRemark){
        SysAuth auth = AuthUtil.getSysExt();
       AgentWithdraw withdraw= agentWithdrawService.getById(id);
       if(withdraw.getAuditResult().intValue()==AgentWithdrawAuditEnum.ADOPT.getValue()){
           return ResultUtil.error("已经审核通过不允许重复");
       }
        agentWithdrawService.audit(id,auditResult,auth,auditRemark);
        return ResultUtil.success();
    }

    /**
     * 代理商提现审核（数据展示）
     *
     * @apiNote 代理商提现审核 agentWithdrawList提现订单集合，agentWithdrawAmount体现总额，agentWithdraw提现具体信息
     * @param id
     * @return
     */
    @PostMapping("withdrawdetails/{id}")
    public Result withdrawdetails(@PathVariable Long id){
        AgentWithdraw agentWithdraw= agentWithdrawService.getById(id);
        AgentRebateQuery agentRebateQuery=new AgentRebateQuery();
        agentRebateQuery.setAgentId(agentWithdraw.getAgentId());
        agentRebateQuery.setOutBillId(agentWithdraw.getId());
        IPage<AgentRebateVo> ttList= agentRebateService.selectListOfPage(initMPage(),agentRebateQuery);
        Map<String,Object> result=new HashMap<String,Object>();
        result.put("agentWithdrawList",ttList);
        result.put("agentWithdrawAmount",agentWithdraw.getAmount());
        result.put("agentWithdraw",agentWithdraw);
        return ResultUtil.success(result);
    }

    /**
     * 代理商提现信息查询
     *
     * @param id   id
     * @return     结果
     */
    @PostMapping("info/{id}")
    public Result<AgentWithdrawSettleVo> agentInfo(@PathVariable Long id){
        return ResultUtil.success(agentWithdrawService.selectAgentSettle(id));
    }

    /**
     * 代理商提现导入模板下载
     * @param response   HttpServletResponse
     */
    @GetMapping("withdrawTemplate")
    public void excel(HttpServletResponse response){
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode("代理商提现导入模板", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), AgentWithdrawExcelDownData.class).sheet("sheet1").doWrite(Lists.newArrayList());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 代理商提现导入
     * @param file  文件
     * @return    结果
     */
    @PostMapping(value = "agentWithdrawImport")
    public  Result agentWithdrawImport(MultipartFile file){
        try {
            EasyExcel.read(file.getInputStream(), AgentWithdrawExcelDownData.class,new AgentWithdrawImportDataListener(agentAccountService,agentService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
           return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.success("success");
    }
}
